// Copyright (c) 2008, 2010 Jeffrey A. Wild

import com.jawild59.gmd5sum.Gmd5SumGui

import groovy.beans.*
import groovy.swing.SwingBuilder

import javax.swing.*
import javax.swing.WindowConstants as WINDOW

import java.awt.*
import java.awt.event.*
import java.awt.font.*
import java.security.MessageDigest

import javax.swing.*
import javax.swing.border.*

class Gmd5sumGuiImpl implements Gmd5SumGui {

	String md5sum(file) {
		assert file != null
		def md = MessageDigest.getInstance("MD5")
		md.update(file.readBytes())
		new BigInteger(1, md.digest()).toString(16)
	}

	void show() {
		
		def model = new Model()

		def swing = new SwingBuilder()
		swing.lookAndFeel 'system'

		def iconImage = new ImageIcon(getClass().getResource("key_lg.gif")).image

		def chooser = {
			def fc = swing.fileChooser()
			def choice = fc.showOpenDialog()		
			if (choice == JFileChooser.APPROVE_OPTION) {
				model.filename = fc.selectedFile.path
				model.sum = md5sum(fc.selectedFile)
			}
			choice
		}

		def exit = {System.exit(0)}

		swing.edt {
			frame(id:'frame', title:'gmd5Sum v2.0', resizable:false, iconImage:iconImage, defaultCloseOperation:WINDOW.EXIT_ON_CLOSE) {
				panel(constraints:BorderLayout.CENTER) {
					gridBagLayout()
					panel(border:BorderFactory.createTitledBorder('File Name'), constraints:new GridBagConstraints(gridx:0, gridy:0)) {
						gridBagLayout()
						textField(id:'filenameTextField', text:bind{model.filename}, preferredSize:new Dimension(280, 20), constraints:new GridBagConstraints(gridx:0, gridy:0, fill:GridBagConstraints.HORIZONTAL, weightx:1))
						button(text:'...', constraints:new GridBagConstraints(gridx:1, gridy:0), actionPerformed:chooser)
					}
					panel(border:BorderFactory.createTitledBorder('MD5 Sum'), constraints:new GridBagConstraints(gridx:0, gridy:1)) {
						gridBagLayout()
						textField(id:'sumTextField', text:bind{model.sum}, preferredSize:new Dimension(325, 20), enabled:false, disabledTextColor:Color.BLACK, constraints:new GridBagConstraints(gridx:0, gridy:0, fill:GridBagConstraints.HORIZONTAL)) 
					}
					panel(border:BorderFactory.createTitledBorder('Compare'), constraints:new GridBagConstraints(gridx:0, gridy:2)) {
						gridBagLayout()
						textField(id:'compareTextField', preferredSize:new Dimension(325, 20), constraints:new GridBagConstraints(gridx:0, gridy:0, fill:GridBagConstraints.HORIZONTAL))
					}
				}
				panel(constraints:BorderLayout.EAST) {
					gridBagLayout()
					label(icon:new ImageIcon(getClass().getResource("key_lg.gif")), constraints:new GridBagConstraints(gridx:0, gridy:0, insets:new Insets(0,0,5,0), weighty:1))
					button(text:'Calculate', constraints:new GridBagConstraints(gridx:0, gridy:1, fill:GridBagConstraints.HORIZONTAL, insets:new Insets(0,0,5,0)), actionPerformed:{
						frame.setCursor(new Cursor(Cursor.WAIT_CURSOR))
						doOutside() {
							def file = new File(filenameTextField.text)
							if (file.exists()) {
								model.sum = md5sum(file)
							} else {
								model.sum = 'invalid file'
							}
							frame.setCursor(new Cursor(Cursor.DEFAULT_CURSOR))
						}
					})
					button(text:'Compare', constraints:new GridBagConstraints(gridx:0, gridy:2, fill:GridBagConstraints.HORIZONTAL, insets:new Insets(0,0,5,0)), actionPerformed:{
						if (sumTextField.text == compareTextField.text) {
							JOptionPane.showMessageDialog(null, 'MD5 Check Sums are the same.', '', JOptionPane.INFORMATION_MESSAGE)
						} else {
							JOptionPane.showMessageDialog(null, 'MD5 Check Sums are different.', '', JOptionPane.ERROR_MESSAGE)
						}
					})
					button(text:'Exit', actionPerformed:exit, constraints:new GridBagConstraints(gridx:0, gridy:3, fill:GridBagConstraints.HORIZONTAL, insets:new Insets(0,0,5,0)))
				}
			}

			if (SystemTray.isSupported()) {
				def popup = swing.popupMenu {
					menuItem(text:'Browse', actionPerformed:{
						if (chooser.call() == JFileChooser.APPROVE_OPTION) {
							 frame.visible = true
						}
					})		
					separator()
					menuItem(text:'Exit', actionPerformed:exit)
				}
				def icon = new ImageIcon(getClass().getResource("key_sm.gif"), "gmd5Sum")
				def trayIcon = new TrayIcon(icon.image, 'gmd5Sum v2.0')
				trayIcon.mouseReleased = {e ->
					if (e.isPopupTrigger()) {
						 popup.location = new Point(e.x, e.y)
						 popup.invoker = popup
						 popup.visible = true
					} else {
						frame.visible = !frame.visible
					}
				}
				SystemTray.systemTray.add(trayIcon)
			}

			frame.pack()
			def screen = Toolkit.defaultToolkit.screenSize
			def x = ((screen.width - frame.width) / 2) as Integer
			def y = ((screen.height - frame.height) / 3) as Integer
			frame.location = new Point(x, y)
			frame.visible = true
		}
	}
}

class Model {
	@Bindable String filename
	@Bindable String sum
}